﻿using MediatR;
using RBAC_Class.Write.API.Application.Command.Permissions;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;

namespace RBAC_Class.API.Application.CommandHandler.Permissions
{
    public class AddPermissionCommandHandler:IRequestHandler<AddPermissionCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly ILogger<AddPermissionCommandHandler> logger;

        public AddPermissionCommandHandler(IBaseRepository<Permission> permissionRep, ILogger<AddPermissionCommandHandler> logger)
        {
            this.permissionRep = permissionRep;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(AddPermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                Permission permission = new Permission()
                {
                    PermissionName = request.PermissionName,
                    PermissionURL = request.PermissionURL,
                    ParentID = request.ParentID,
                    CreateTime = DateTime.Now,
                    IsDelete = false
                };
                permissionRep.Add(permission);
                return Task.FromResult(new APIResult<int>()
                {
                    Code = ResultCode.Success,
                    Message = "添加成功",
                    Data = 1
                });
            }
            catch (Exception ex)
            {
                logger.LogError("添加出错", ex);
                throw;
            }
            
        }
    }
}
